
<template>
  <div class="employees-container">
    <div class="app-container">
      <PageTools title="数据100条">
        <!-- v-if="$store.state.user.userInfo.roles.points.includes('import_excel')" -->
        <!-- 权限级按钮  v-allow="'import_excel'" 通过注册全局组件 完成 -->
        <el-button
          v-allow="'import_excel'"
          type="warning"
          size="small"
          @click="$router.push('/import')"
        >excel导入</el-button>
        <el-button
          v-allow="'export_excel'"
          type="danger"
          size="small"
          @click="hExportExcel"
        >excel导出</el-button>
        <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
      </PageTools>
      <el-card style="margin-top: 10px">
        <!-- :default-sort="{prop: 'workNumber'}"  页面一加载默认进行排序 -->
        <el-table border :data="list" :default-sort="{prop: 'workNumber'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="staffPhoto">
            <template slot-scope="scope">
              <!-- <img :src="scope.row.staffPhoto"> -->
              <ImageHolder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template slot-scope="scope">
              <!-- {{ scope.row.formOfEmployment===1? '正式': '非正式' }}  -->
              {{ format(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <!-- sortable  添加排序按钮 -->
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id='+scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!--  分页 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            :total="total"
            :current-page="page"
            :page-size="size"
            :page-sizes="[2, 5, 10, 20]"
            background
            layout="total, sizes, prev,pager,next"
            @current-change="hCurrentChange"
            @size-change="hSizeChanges"
          />
        </el-row>
      </el-card>
    </div>
    <el-dialog
      title="添加"
      :visible.sync="showDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <Employees
        v-if="showDialog"
        @success="hSuccess"
        @close="hClose"
      />
    </el-dialog>
    <!-- 分配角色 -->
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialogRole"
    >
      <AssignRole
        v-if="showDialogRole"
        :employee-id="curEmployeId"
        @success="hSuccessRole"
      />
    </el-dialog>

  </div>
</template>
<script>
//  引入分配角色组件
import AssignRole from './components/assignRole.vue'
const TYPE_MAP = { 1: '正式', 2: '非正式 ', 3: ' ddd' } // return  TYPE_MAP[type] || '未知'
import { getEmployeeList, delEmployee } from '@/api/employees'
import Employees from './empDialog.vue'
export default {
  components: { Employees, AssignRole },
  data() {
    return {
      showDialogRole: false, // 分配角色
      showDialog: false, // 添加弹层
      total: 0,
      page: 1,
      size: 5,
      list: [],
      curEmployeId: '' // 当前员工编号
    }
  },
  created() {
    this.loadEmployeeList()
  },

  methods: {
    hSuccessRole() {
      this.showDialogRole = false

      this.$message.success('保存成功')
    },
    hAssignRole(id) {
      this.showDialogRole = true
      this.curEmployeId = id
      // console.log(id)
    },

    // rows: [{mobile:'13600000001', usename:'吕勇锐'}, {mobile:'13600000002', usename:'袁永安'}]
    //
    // data:
    //  [
    //   ["13600000001", "吕勇锐"]
    //   ["13600000002", "袁永安"]
    //  ]
    formatDate(rows) {
      // 表头
      const enHeader = Object.keys(rows[0])
      // const header = Object.keys(rows[0])
      const mapObj = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const header = enHeader.map(en => mapObj[en])
      // 内容
      // const data = rows.map(obj=> { return  Object.values(obj)} )
      const data = rows.map(obj => {
        // 把聘用格式进行转换
        // obj.formOfEmployment ====> 1, 2
        obj.formOfEmployment = TYPE_MAP[obj.formOfEmployment]
        return Object.values(obj)
      })
      return { header, data }
    },
    async hExportExcel() {
      // 1. 发送请求拿数据
      const res = await getEmployeeList({ page: this.page, size: this.size })
      console.log(res)
      //  2.对数据进行格式化
      const { header, data } = this.formatDate(res.data.rows)
      //  3. 导出
      console.log('员工信息', header, data)

      import('@/vendor/Export2Excel').then(excel => {
        // excel表示导入的模块对象
        console.log(excel)
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    // 子传父-点击取消
    hClose() {
      // 1. 关闭弹层
      this.showDialog = false
    },
    // 子传父-点击确定
    hSuccess() {
      // 1. 关闭弹层
      this.showDialog = false
      //  添加成功后 , 进入最后一页
      this.total++
      this.page = Math.ceil(this.total / this.size)
      // 2.重新发送请求
      this.loadEmployeeList()
    },
    // 删除
    async doDel(id) {
      // 1. 发送请求
      await delEmployee(id)
      // 判断如果当前删除的是最后一页 如果是页码就-1
      if (this.list.length === 1 && this.page > 1) {
        this.page--
      }
      // 2. 删除提示
      this.$message.success('删除成功')
      // 3. 重新 刷新页面
      this.loadEmployeeList()
    },
    // 用户点击了删除
    hDel(id) {
      // 1. 提示
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示').then(() => {
        this.doDel(id)
      }).catch()
    },
    format(type) {
      // if(type === 1 ){
      //   return '正式'
      // } else if(type ===2 ){
      //    return '非正式'
      // }else if(type ===3 ){
      //    return '123'
      // } 或
      return TYPE_MAP[type] || '未知'
    },
    async loadEmployeeList() {
      const res = await getEmployeeList({ page: this.page, size: this.size })
      console.log(res)
      this.list = res.data.rows
      this.total = res.data.total
    },
    hCurrentChange(curPage) {
      // 1.跟新页码
      this.page = curPage
      // 2.重新发送请求
      this.loadEmployeeList()
    },
    // 跟改每页显示几条数据
    hSizeChanges(curPagesize) {
      // 1.跟新数据
      this.page = 1
      this.size = curPagesize
      // 2. 重发请求
      this.loadEmployeeList()
    }
  }
}
</script>
